package easy;

import java.util.HashMap;
import java.util.Map;

public class Solution_290 {

    public static boolean wordPattern(String pattern, String s) {
        Map<Character, String> map = new HashMap<>();
        Map<String, Character> map2 = new HashMap<>();
        int patternLength = pattern.length();
        int length = s.length();
        char[] chars = s.toCharArray();
        StringBuffer buffer = new StringBuffer();
        int i = 0, j = 0;
        for (; i < length && j < patternLength; i++) {
            if (chars[i] == ' ') {
                if (buffer.length()==0) {
                    continue;
                }
                char key = pattern.charAt(j);
                String value = buffer.toString();
                if (map.containsKey(key) || map2.containsKey(value)) {
                    if (!value.equals(map.get(key)) || !(key ==map2.get(value))) {
                        return false;
                    }
                } else {
                    map.put(key, value);
                    map2.put(value, key);
                }
                j++;
                buffer.delete(0, buffer.length());
            } else {
                buffer.append(chars[i]);
            }
        }
        if (buffer.length()!=0) {
            char key = pattern.charAt(j);
            String value = buffer.toString();
            if (map.containsKey(key) || map2.containsKey(value)) {
                if (!value.equals(map.get(key)) || !(key ==map2.get(value))) {
                    return false;
                }
            } else {
                map.put(key, value);
                map2.put(value, key);
            }
            j++;
        }
        return i==length && j==patternLength;
    }

    public static void main(String[] args) {
        System.out.println(wordPattern("abc", "dog cat dog"));
    }
}
